package org.app.appjson.adapter;

import org.app.appjson.exception.AppJsonException;
import org.app.appjson.reader.JsonLexer;
import org.app.appjson.reader.JsonToken;
import org.app.appjson.reader.ReadHandler;
import org.app.appjson.writer.WriteHandler;

/**
 * Float类型适配器
 * @author lizhongsi
 * @version 1.0
 * @since 1.0
 */
public class FloatAdapter implements TypeAdapter {

    public static Float read(ReadHandler handler) throws AppJsonException {
        JsonLexer lexer = handler.getLexer();
        if (lexer.peek().getType() == JsonToken.NULL) {
            lexer.next();
            return null;
        }
        if (lexer.peek().getType() == JsonToken.NUMBER) {
            return Float.valueOf(lexer.next().getValue());
        }
        throw new AppJsonException("FloatAdapter exception. the type of token isn't NUMBER.");
    }

    public static void write(WriteHandler handler) throws AppJsonException {
        Object object = handler.getObject();
        if (!(object instanceof Float)) {
            throw new AppJsonException("Object is not Byte type.");
        }
        handler.write(String.valueOf(object));
    }
}
